﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hired.Classes;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.Globalization;
using System.IO;
using System.Xml.Linq;
using System.Xml;

namespace Hired
{
    public partial class createaccount : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // loading countries from countries.xml
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("countries.xml"));

            foreach (XmlNode node in doc.SelectNodes("//country"))
            {
                ddlCountryOfResidence.Items.Add(new ListItem(node.InnerText));
            }

            // checking cblAccountSettings
            foreach (ListItem li in cblAccountSettings.Items)
            {
                li.Selected = true;
            }
        }

        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            if (Page.IsValid)
            {
                JobseekerAccount account = new JobseekerAccount();
                Jobseeker jobseeker = new Jobseeker();

                #region Converting field values to code attributes

                //attributes(Jobseeker)
                jobseeker.Address = txtAddress1.Text + " " + txtAddress2.Text + " " + txtAddress3.Text;
                jobseeker.CountryOfResidence = ddlCountryOfResidence.Text;
                jobseeker.EducationLevel = ddlEducationLevel.Text;
                jobseeker.FirstName = txtFirstName.Text;
                switch (ddlGender.Text)
                {
                    case "Male":
                        jobseeker.Gender = "M";
                        break;
                    case "Female":
                        jobseeker.Gender = "F";
                        break;
                }
                jobseeker.HomeNumber = txtHomeNumber.Text;
                jobseeker.LastName = txtLastName.Text;
                jobseeker.MobileNumber = txtMobileNumber.Text;
                jobseeker.Nationality = txtNationality.Text;
                jobseeker.PreviousEducationalInstitute = txtPreviousEducationalInstitute.Text;
                jobseeker.Specialization = ddlSpecialization.Text;
                jobseeker.CurrentEmployment = txtCurrentEmployment.Text;
                jobseeker.PreviousEmployment = txtPreviousEmployment.Text;
                jobseeker.PostalCode = txtPostalCode.Text;
                jobseeker.ImageAddress = "images/ProfilePic.png";
                jobseeker.WebsiteURL = txtWebsiteURL.Text;

                // attributes(account)
                account.Activated = false;
                account.Username = txtUsername.Text;
                account.Password = Encryption.md5Encrypt(txtPassword.Text);
                account.PrivacySettings = 0;
                account.Email = txtEmail.Text;
                account.SecurityQuestion = ddlSecurityQuestion.Text;
                account.SecurityAnswer = txtSecurityAnswer.Text;
                account.AllowMessages = cblAccountSettings.Items[0].Selected;
                account.AllowNotifications = cblAccountSettings.Items[1].Selected;

                // date of birth
                string stringDOB = txtDateOfBirth.Text;
                CultureInfo ci = new CultureInfo("es-ES");
                DateTime inputDOB = DateTime.Parse(stringDOB, ci);
                jobseeker.DateOfBirth = inputDOB;
                #endregion

                if (DBJobseekerAccount.addJobseekerAccount(account, jobseeker))
                {
                    JobseekerAccount jsa = DBJobseekerAccount.retrieveJobseekerAccountbyUsername(txtUsername.Text, true);
                    // file upload
                    // fileUploadResume
                    string resumePathname = Server.MapPath("/Resumes/" + jsa.JAccountID + "/");
                    if (!Directory.Exists(resumePathname))
                    {
                        System.IO.Directory.CreateDirectory(resumePathname);
                        if (fileUploadResume.HasFile)
                        {
                            string fileservername = fileUploadResume.FileName;
                            resumePathname += fileservername;
                            HttpPostedFile f = fileUploadResume.PostedFile;
                            if (checkFileExt(f))
                            {
                                fileUploadResume.SaveAs(resumePathname);
                                jobseeker.ResumeAddress = resumePathname;
                            }
                            else {
                                lblResumeUploadError.Visible = true;
                            }
                        }
                    }
                    else
                    {
                        lblResumeUploadError.Visible = true;
                    }
                    //send email
                    Send(account.Email);
                    Response.Redirect("registersuccess.aspx");
                }
            }
        }

        //username
        public bool checkUsername()
        {
            if (DBAccount.RetrieveAccountByUsername(txtUsername.Text) == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool checkEmail()
        {
            if (DBAccount.RetrieveAccountByEmail(txtEmail.Text) == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        //postal code
        public Boolean checkPostalCode()
        {
            if (txtPostalCode.Text.Length != 6)
            {
                return false;
            }

            else
            {
                return true;
            }
        }

        //Email
        public void Send(string recipient)
        {
            string from = ConfigurationManager.AppSettings["Username"];
            string server = ConfigurationManager.AppSettings["MailServer"];
            string password = ConfigurationManager.AppSettings["password"];


            MailMessage mail = new MailMessage(from, recipient);
            SmtpClient smtp = new SmtpClient(server, 587);
            NetworkCredential nc = new NetworkCredential(from, password);

            mail.Subject = "Welcome to Hired. Please activate your account.";
            mail.IsBodyHtml = true;
            mail.Body = "Thank you for registering with Hired <br /><br /> Your username:" + txtUsername.Text + "<br />Password:" + txtPassword.Text
                + "<br /><br />You can activate your account @ http://hired.com/activate.aspx?username=" + txtUsername.Text + "&activationID=" + Encryption.md5Encrypt(txtUsername.Text)
                + "<br /><br />If you have trouble activating your account. Please go to <a href=\"http://hired.com/activate.aspx\">here</a>"
                    + "<br />Your activation ID:" + Encryption.md5Encrypt(txtUsername.Text);

            smtp.EnableSsl = true;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = nc;

            try
            {
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }


        //date of birth
        public Boolean checkDateOfBirth(DateTime dateOfBirth)
        {
            DateTime now = DateTime.Today;
            int age = now.Year - dateOfBirth.Year;

            if (dateOfBirth > now.AddYears(-age))
            {
                age--;
            }
            DateTime d = DateTime.Now;
            if (age >= 16)
            {
                //user is allowed, congrats!
                return true;
            }
            else
            {
                
                return false;
            }
        }

        //Checkfilext

        public Boolean checkFileExt(HttpPostedFile fileUpload)
        {
            if (fileUpload != null && fileUpload.ContentLength > 0)
            {
                FileInfo finfo = new FileInfo(fileUpload.FileName);
                string fileExtension = finfo.Extension.ToLower();
                if (fileExtension == ".doc" || fileExtension == ".docx" || fileExtension == ".pdf" || fileExtension == ".odt")
                {
                    return true;
                }
                else {
                    return false;
                }                
            }
            else
            {
                return false;
            }
        }

        protected void CustomUsername_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = checkUsername();
        }

        protected void CustomEmail_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = checkEmail();
        }

        protected void CustomDOB_ServerValidate(object source, ServerValidateEventArgs args)
        {
            string stringDOB = txtDateOfBirth.Text;
            CultureInfo ci = new CultureInfo("es-ES");
            DateTime inputDOB = DateTime.Parse(stringDOB, ci);

            args.IsValid = checkDateOfBirth(inputDOB);
        }
    }
}



